// 统一请求工具
export const BASE_URL = "https://wocti.com";
// export const BASE_URL = "http://localhost:3006";

// 请求拦截器
const request = (options) => {
  return new Promise((resolve, reject) => {
    // 获取token
    const token = uni.getStorageSync("token") || "";

    // 构建请求配置
    const config = {
      url: BASE_URL + options.url,
      method: options.method || "GET",
      data: options.data || {},
      header: {
        "Content-Type": "application/json",
        Authorization: token ? `Bearer ${token}` : "",
        ...options.header,
      },
      success: (res) => {
        // 统一处理响应
        if (res.statusCode === 401) {
          // token过期，跳转登录
          uni.removeStorageSync("token");
          uni.removeStorageSync("userInfo");
          uni.showToast({
            title: "登录已过期，请重新登录",
            icon: "none",
          });
          setTimeout(() => {
            uni.reLaunch({
              url: "/pages/login/login",
            });
          }, 1500);
          reject(res);
        } else if (res.statusCode === 500) {
          uni.showToast({
            title: res.data?.data?.message || "请求失败",
            icon: "none",
          });
          reject(res);
        } else {
          resolve(res.data);
        }
      },
      fail: (err) => {
        uni.showToast({
          title: "网络请求失败",
          icon: "none",
        });
        reject(err);
      },
    };

    uni.request(config);
  });
};

export default request;
